import { Injectable } from '@angular/core';
import{ SQLiteObject, SQLite }from '@ionic-native/sqlite';
import { Platform } from 'ionic-angular/platform/platform';


@Injectable()
export class SqliteHelperProvider {
 
  //sqlite_native不支持Browser
  //在Browser端使用webSQL(W3C废弃的规范)
  database:SQLiteObject;
  win_db:any;//H5环境下的数据对象
  win : any = window;//window对象

  constructor(private sqlite: SQLite,private platform:Platform) {
    
  }

/**
 * 创建或打开数据库
 */
 creatOrOpenDb(): Promise<any>{
   return new Promise<any>((resolve,reject)=>{
     if(this.isMobile()){
    this.sqlite.create({name: 'park_data_1.db',location:'default'})
    .then((db:SQLiteObject)=>{
      this.database = db;
      //创建数据表的SQL语句
      this.createTable().then(res=>resolve(res),err=>reject(err));
    }) 
    .catch(e=>{
      console.error(e);
      reject(e);
    })
     } else{
       this.win_db = this.win.openDatabase('park_data_4.db','1.0','景区信息表',60*1024*1024);
       //创建数据表的SQL语句
       this.createTable().then(res=>resolve(res),err=>reject(err));
     }
   }); 
 }
/**
 * 创建数据表
 */
 createTable(): Promise<any>{
   let sql: string = 'CREATE TABLE IF NOT EXISTS parks_lite(objectId TEXT, name TEXT, point TEXT)';
   return this.executeSql(sql,[]);
  }
/**
 * 执行sql语句
 * @param sql 
 * @param params 
 */
  executeSql(sql:string,params: Array<any>): Promise<any>{
   if(this.isMobile()){
     if(this.database){
      return this.execLoaclSql(sql,params);
     }
   }else{
     if(this.win_db){
     return this.execWebSql(sql,params);
         }
   }
   return new Promise(resolve=>resolve([]));
  }
/**
 * 执行基于本地SQLite的SQL语句
 * @param sql 
 * @param params 
 */
  private execLoaclSql(sql:string , params : Array<any>):Promise<any>{
    return this.database.executeSql(sql,params);
  }
/**
 * 执行基于Web SQL的SQL语句
 * @param sql 
 * @param params 
 */
 private execWebSql(sql: string,params : Array<any>):Promise<any>{
    return new Promise((resolve,reject)=>{
    this.win_db.transaction(tx=>{
      tx.executeSql(sql,params,(tx,res)=>resolve(res),(tx,err)=>reject
      (err));
    },err => reject(err));
   });
  }

/**
 * 判定是否为真机环境
 */
 isMobile(): boolean{
   return this.platform.is('mobile')&& !this.platform.is('mobileweb');
 }

}
